const {app,BrowserWindow,dialog,Menu,MenuItem,ipcMain,shell} = require('electron')
const path = (dir) => require('path').join(__dirname, dir)
const fs = require('fs')

//变量
let env=app.isPackaged?'prod':'test'
let win=null,icon=path('app/icon.ico')
let version=JSON.parse(fs.readFileSync(path('app/version.json')))
let config=JSON.parse(fs.readFileSync(path('app/config.json')))
let globalData={
  save:JSON.parse(fs.readFileSync(path('app/save.json'))),
  selSave:null,
  troops:null,
  server:null,
  netgame:null
}

//jv update
let jvJson=JSON.parse(fs.readFileSync(path('app/jv.json')))
let jvUpdate=(i)=>{
  fs.exists(path('app/jv/'+i+'.js'), function(exists) {
    if(exists){
      require(path('app/jv/'+i))
      jvJson.finish=i
      fs.writeFileSync(path('app/jv/jv.json'),JSON.stringify(jvJson))
      jvUpdate(i+1)
    }
  })
}
jvUpdate(jvJson.finish+1)

//====================窗体====================
  function createWindow () {
    win = new BrowserWindow({
      width: 1600,
      height: 950,
      icon: icon,
      title:'梦幻模拟战2',
      webPreferences: {
        nodeIntegration: true,
        backgroundThrottling:false,
      }
    })

    win.loadFile(path('src/main/index.html'))

    if(env=='test'){
      win.webContents.openDevTools()
      require('electron-connect').client.create(win)

      Menu.setApplicationMenu(Menu.buildFromTemplate([
        {
          label: '菜单',
          submenu:[
            {
              label: 'game',
              click: () => {
                win.loadFile(path('src/main/game.html'))
              }
            },
            {
              label: '返回主菜单',
              click: () => {
                win.loadFile(path('src/main/index.html'))
              }
            }
          ]
        },
        {
          label: '开发者工具',
          click: () => {
            win.webContents.openDevTools()
          }
        }
      ]))
    }else{
      Menu.setApplicationMenu(Menu.buildFromTemplate([{
        label: '开发者工具',
        click: () => {
          win.webContents.openDevTools()
        }
      }]))
    }
  }

//====================通信====================
  //返回环境
  ipcMain.on('getEnv', (event, arg) => {
    event.returnValue = env
  })
  //全局变量
  ipcMain.on('setData', (event, arg) => {
    globalData[arg[0]]=arg[1]
  })
  ipcMain.on('getData', (event, arg) => {
    event.returnValue = globalData[arg]
  })
  //获取版本信息
  ipcMain.on('getVersion', (event, arg) => {
    event.returnValue = version
  })
  //获取配置信息
  ipcMain.on('getConfig', (event, arg) => {
    event.returnValue = config
  })
  //保存存档
  ipcMain.on('save', (event, arg) => {
    //新游戏
    if(arg.r=='new'){
      let hero=JSON.parse(fs.readFileSync(path('src/asset/data/role/hero/wo.json')))
      let temp={
        name:arg.name,
        level:1,
        shop:true,
        xlevel:[],
        item:[],
        money:500,
        exp:0,
        hero:{
          '艾尔文':hero['艾尔文'],
          '海恩':hero['海恩']
        }
      }
      globalData.save[arg.id]=temp
      fs.writeFileSync(path('app/save.json'),JSON.stringify(globalData.save))
      //设置当前存档
      globalData.selSave=JSON.parse(JSON.stringify(globalData.save[arg.id]))
    }
    
    //保存游戏
    if(arg.r=='save'){
      //获取当前使用的存档数据
      globalData.save[arg.id]=JSON.parse(JSON.stringify(globalData.selSave))
      //保存
      globalData.save[arg.id].shop=arg.shop
      globalData.save[arg.id].role=arg.role
      globalData.save[arg.id].round=arg.round
      globalData.save[arg.id].finish=arg.finish
      globalData.save[arg.id].lvjs=arg.lvjs
      fs.writeFileSync(path('app/save.json'),JSON.stringify(globalData.save))
    }
  })
  //读取游戏
  ipcMain.on('load', (event, arg) => {
    //将选取的存档设为选择存档
    globalData.selSave=JSON.parse(JSON.stringify(globalData.save[arg]))
  })
  //获取存档信息
  ipcMain.on('getSave', (event, arg) => {
    if(arg){
      event.returnValue = globalData.save[arg]
    }
    event.returnValue = globalData.save
  })
  //保存配置信息
  ipcMain.on('saveConfig', (event, arg) => {
    config[arg[0]]=arg[1]
    fs.writeFileSync(path('app/config.json'), JSON.stringify(config))
  })
  //退出
  ipcMain.on('exit', (event, arg) => {
    win.destroy()
  })
  //更新
  ipcMain.on('update', (event, arg) => {
    dialog.showMessageBox({
      icon:icon,
      buttons:['确定','取消'],
      title:'消息',
      message:'程序有更新，是否退出并更新程序？',
      detail:'注意：更新失败可以重新运行\\resources\\app.asar.unpacked\\app\\update.exe'
    }).then(o=>{
      if(o.response==0){
        //更新
        shell.openPath(__dirname+'\\..\\..\\resources\\app.asar.unpacked\\app\\update.exe')
        win.destroy()
      }
    })
  })

//====================app====================
  app.whenReady().then(createWindow)

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })